import hccmConfig from './hccm-config.js'
import hccmStore from './hccm-store.js'

const normalLoading = '正在加载...'


/**
 * 上传图片
 */
 const uploadImage = (path, callback) => {
	let promise = new Promise(function(success, fail) {
		var header = {}
		uni.request({
			url: hccmConfig.HCCM_HOST_URL + '/js/api/common/uploadFile/getToken', //仅为示例，并非真实接口地址。
			data: {
				fileType: 'png'
			},
			header: {},
			success: (res) => {
				console.log("===========getToken=========");
				console.log(res.data);
				if (res.statusCode == 200 && res.data.code == 200) {
					const uploadTask = uni.uploadFile({
						url: hccmConfig.qiniuUrl,
						filePath: path,
						name: 'file',
						formData: {
							"key": res.data.data.key,
							"token": res.data.data.token
						},
						success: (res) => {
							console.log("=====图片上传返回=====")

							//优化展示，因为4g网络进度到99的时候会卡很久，所以加一个成功的进度状态，让前端知道什么时候成功
							if(callback){
								callback({
									progress: 101
								})
							}
							console.log(res)
							let backData = JSON.parse(res.data);
							let filePath = '';
							let message = '';
							if (res.statusCode == 200) {
								filePath = hccmConfig.imgHostUrl + '/' + backData
									.key;
							} else {
								message = backData.error;
							}

							//此步骤是为了把数据处理成之前hccm的文件上传的格式，可以防止后面使用该方法的兼容性问题
							let dataData = {
								code: res.statusCode,
								message: message,
								data: {
									filePath: filePath
								}
							}
							let rData = {
								statusCode: res.statusCode,
								data: JSON.stringify(dataData)
							}
							success(rData);
						},
						fail: (err) => {
							console.log("=====3333=====")
							fail(err)
						}
					});

					uploadTask.onProgressUpdate((res) => {
						// console.log('上传进度' + res.progress);
						// console.log('已经上传的数据长度' + res.totalBytesSent);
						// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
						// 测试条件，取消上传任务。
						// if (res.progress > 50) {
						// 	uploadTask.abort();
						// }

						if (callback) {
							callback(res);
						}
					});
				} else {
					fail(res)
				}
			},
			fail: (err) => {
				console.log("=====3333=====")
				fail(err)
			}
		});
	})
	return promise
};


//hccm登录机制，使用改方法，需要配合个人中心组件
const hccmrequest = (args) => {
	//配置默认参数
	var url, param, header, method;
	url = args['url'] || '';
	param = {};
	var data_params = args['param'] || {};
	param = data_params;
	method = args['method'] || 'GET';
	if (method == 'GET' || method == 'get') {
		header = {
      'Content-Type': 'application/json',
      token: hccmStore.getPhoneToken(),
			version: '2.0'
    }
	} else if (method == 'POST' || method == 'post') {
		header = {
      'Content-Type': 'application/json',
      token: hccmStore.getPhoneToken(),
			version: '2.0'
    }
	}
	var mHeader= args['header'];
	if(mHeader){
		header=mHeader;
	}
	// param['__ajax']='json';
	// if(hccmStore.getSessionId()){
	// 	param['__sid']=hccmStore.getSessionId();
	// }
	// // 有些接口不需要userId
	// if(hccmStore.getUser().id && !args.param.unUserId){
	// 	param['userId']=hccmStore.getUser().id;
	// }
	
	// param['corpCode_'] = hccmConfig.corpCode;
	// param['corpName_']=hccmConfig.corpName;
	
	let httpDefaultOpts = {
		url: url,
		data: param,
		method: method,
		header: header,
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				var newRes=res;
				if(res[1].statusCode==200&&res[1].data&&res[1].data.result=='login'){
					refreshSid().then(
						res => {
							if(res.statusCode==200&&res.data&&res.data.result=='true'&&res.data.sessionid){
								console.log("====setSessionId===="+res.data.sessionid)
								hccmStore.setSessionId(res.data.sessionid);
								hccmrequest(args).then(
									res => {
										console.log("=======res======");
										console.log(res);
										resolve(res);
									},
									error => {
										toLogin()
									})
							}else{
								toLogin()
							}
						},
						error => {
							toLogin()
						})
				}else{
					resolve(res[1]);
				}
			}
		).catch(
			(error) => {
				reject(error)
			}
		)
	})
	return promise
};



const refreshSid = () =>{
	var header = {
		"Content-Type": "application/x-www-form-urlencoded"
	};
	var param={
		"appType":"wx_lite",
		"socialId":hccmStore.getSocialId(),
		"uid":hccmStore.getWxOpenId()
	}
	let httpDefaultOpts = {
		url: hccmConfig.HCCM_HOST_URL + '/js/api/common/user/refreshSid',
		data: param,
		method: "GET",
		header: header
	}
	return uni.request(httpDefaultOpts).then(
			(res) => {
				console.log("======refreshSid=====");
				console.log(res[1]);
				return res[1];
			}
		).catch(
			(error) => {
				console.log("======refreshSid error=====");
				console.log(error);
				return error;
			}
		)
};

const toLogin = () => {
	uni.hideLoading()
	uni.redirectTo({
		url: '/pages/hccm-patient-manage/pages/login/login'
	})
}

// 安全取值
function get(source, path, defaultValue = undefined) {
	// a[3].b -> a.3.b
	const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.')
	let result = source
	for (const p of paths) {
		result = Object(result)[p]
		if (result === undefined) {
			return defaultValue
		}
	}
	return result;
}
// 获取对象类型
const getType = (o) => Object.prototype.toString.call(o).toLocaleLowerCase().slice(1, -1).split(' ')[1];
// 是否字符串
const isString = (o) => getType(o) == 'string';
// 是否对象
const isObject = (o) => getType(o) == 'object';
// 是否布尔类型
const isBoolean = (o) => getType(o) == 'boolean';
// 弹框提示
const showError = (msg = '') => msg.length > 20 ? uni.showModal({
	content: msg,
	showCancel: false
}) : uni.showToast({
	icon: 'none',
	title: msg || '服务异常'
});
// 获取错误信息 弹框提示
const showErrorServer = (res) => showError(get(res, 'data.message') || get(res, 'data.msg') || get(res, 'data.mes') ||
	'服务异常');

/**
 *  改接口做了loading逻辑和返回错误提示的封装
 * 
 *  接口封装调用的方法如下
 * 
 * 	url：不是http开头的默认是HOST_URL前缀
 * 	method：请求的类型，get/post
 * 	param：参数
 * 
 * 	loadingTip：
 *  true：展示默认的normalLoading  不传或者false：不展示loading  
 * 	loadingTip是String类型，loadling的title以loadingTip为准
 * 
 * 	hideErrorMsg 是否展示错误信息，默认是展示
 */
let execApi = (url, method, param, loadingTip, hideErrorMsg = false, header) => {
	let tip = isBoolean(loadingTip) ? loadingTip ? normalLoading : '' : loadingTip;
	tip && uni.showLoading({
		title: tip
	});
	// let headerObj = {}
	// if(header){
	// 	headerObj = header
	// }
	let requestUrl = url.indexOf("http") == 0 ? url : hccmConfig.HCCM_HOST_URL + url;
	return new Promise((resolve, reject) => {
		hccmrequest({
      url: requestUrl,
      method: method,
      param: param,
      header: header,
      // header:Object.assign(
      // 	headerObj,
      // 	{token : '123'}
      // )
    }).then(
      res => {
				tip && uni.hideLoading()
        try {
					if (res.statusCode == 200 && (res.data.code == 200 || res.data.result == 'true' || res.data.msg == 'success')) {
            resolve(res.data)
          } else {
            !hideErrorMsg && showErrorServer(res)
            reject(res)
          }
        } catch (e) {
          reject(res)
        }
      },
      err => {
        uni.hideLoading()
        showErrorServer(err)
        reject(err)
      },
    )
	}, err => {
		tip && uni.hideLoading();
		reject(err);
	});
}

/**
 * url不是http开头的  用HCCM_HOST_URL  
 * 
 * loadingTip  
 * true：展示默认的normalLoading  不传或者false：不展示loading  
 * loadingTip是String类型，loadling的title以loadingTip为准
 * 
 * hideErrorMsg 是否展示错误信息，默认是展示
 */
let postApi = (url, param, loadingTip,hideErrorMsg = false, header) => {
	return execApi(url, "POST", param, loadingTip,hideErrorMsg,header)
}

let getApi = (url, param, loadingTip,hideErrorMsg = false, header) => {
	return execApi(url, "GET", param, loadingTip,hideErrorMsg,header)
}



export default {
	uploadImage, //上传图片
	postApi, //post请求
	getApi, //get请求
};
